package huyaoying.study.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * Java NIO管道
 * Java NIO管道用于在两个线程之间建立单向数据连接。它有一个槽通道和源通道。数据正在写入槽通道，然后可以从源通道读取该数据
 *
 * @author huyaoying
 * @date 2022/2/8
 */
public class PipeExample {

    public static void main(String[] args) throws IOException {
        // The Pipe is created
        Pipe pipe = Pipe.open();
        // 槽通道 写入数据
        Pipe.SinkChannel skChannel = pipe.sink();
        String td = "Data is successfully sent for checking the java NIO Channel Pipe.";
        ByteBuffer bb = ByteBuffer.allocate(512);
        bb.clear();
        bb.put(td.getBytes());
        bb.flip();
        // write the data into a sink channel.
        while (bb.hasRemaining()) {
            skChannel.write(bb);
        }

        // 源通道 读取数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        bb = ByteBuffer.allocate(512);
        // The data is write to the console
        while (sourceChannel.read(bb) > 0) {
            bb.flip();

            while (bb.hasRemaining()) {
                char testData = (char) bb.get();
                System.out.print(testData);
            }
            bb.clear();
        }
    }
}
